package com.qiaofang.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wenhao.jpa.Specifications;
import com.google.common.collect.Lists;
import com.qiaofang.common.constant.DelFlagEnum;
import com.qiaofang.common.constant.ExceptionEnum;
import com.qiaofang.common.constant.IsLinkM2Enum;
import com.qiaofang.common.constant.YesOrNoEnum;
import com.qiaofang.common.exception.BusinessException;
import com.qiaofang.common.exception.SystemException;
import com.qiaofang.common.model.PageDTO;
import com.qiaofang.common.model.UiListBean;
import com.qiaofang.common.response.CommonResponse;
import com.qiaofang.common.utils.DateUtil;
import com.qiaofang.common.utils.HttpUtil;
import com.qiaofang.common.utils.PageUtil;
import com.qiaofang.common.utils.StringUtil;
import com.qiaofang.constant.CompanyTypeEnum;
import com.qiaofang.constant.LogoTypeEnum;
import com.qiaofang.constant.OperationTypeEnum;
import com.qiaofang.constant.StatusEnum;
import com.qiaofang.dto.BaseResponseDto;
import com.qiaofang.dto.CompanyDTO;
import com.qiaofang.dto.ListApiLogDTO;
import com.qiaofang.dto.ListCompanyDTO;
import com.qiaofang.entity.*;
import com.qiaofang.repository.ApiLogRepository;
import com.qiaofang.repository.CompanyRepository;
import com.qiaofang.repository.LogoRepository;
import com.qiaofang.repository.OtherCompanyRepository;
import com.qiaofang.service.*;
import com.qiaofang.vo.ApiLogVO;
import com.qiaofang.vo.CompanyVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class ApiLogServiceImpl implements ApiLogService {

    @Autowired
    private ApiLogRepository apiLogRepository;
    @Autowired
    private OtherCompanyRepository otherCompanyRepository;

    @Override
    public UiListBean listApiLog(ListApiLogDTO dto, PageDTO page) {
        Specification<ApiLog> specification = Specifications.<ApiLog>and()
                .between(StringUtil.isNotBlank(dto.getCreateTimeStart()), "createTime"
                        , DateUtil.minOfString(dto.getCreateTimeStart()),
                        DateUtil.maxOfString(dto.getCreateTimeEnd()))
                .predicate(StringUtil.isNotBlank(dto.getApiType()) && "1".equals(dto.getApiType()),
                        Specifications.or()
                                .like("url", StringUtil.addLikeParam("http://open-api"))
                                .build())
                .predicate(StringUtil.isNotBlank(dto.getApiType()) && "2".equals(dto.getApiType()),
                        Specifications.or()
                                .like("url", StringUtil.addLikeParam("channel-openapi"))
                                .build())
                .predicate(StringUtil.isNotBlank(dto.getSearchContent()),
                        Specifications.or()
                                .like("requestContent", StringUtil.addLikeParam(dto.getSearchContent()))
                                .build())
                .build();
        Page<ApiLog> apiLogs = apiLogRepository.findAll(specification, PageUtil.getPageByDTO(page, PageUtil.getCreateTimeDesc()));

        UiListBean<ApiLogVO> uiListBean = new UiListBean();
        uiListBean.setList(convertListDomain2VO(apiLogs.getContent()));
        uiListBean.setTotalCount(apiLogs.getTotalElements());
        return uiListBean;
    }

    private List<ApiLogVO> convertListDomain2VO(List<ApiLog> apiLogs) {
        List<ApiLogVO> vos = Lists.newArrayList();
        if (apiLogs != null) {
            for (ApiLog apiLog : apiLogs) {
                ApiLogVO vo = convertDomain2VO(apiLog, false);
                vos.add(vo);
            }
        }
        return vos;
    }

    private ApiLogVO convertDomain2VO(ApiLog apiLog, boolean extend) {
        ApiLogVO vo = new ApiLogVO();
        vo.setId(apiLog.getId());
        vo.setUrl(apiLog.getUrl());
        vo.setCreateTime(apiLog.getCreateTime());
        vo.setRequestContent(apiLog.getRequestContent()==null ? "":apiLog.getRequestContent());
        int uuidIndex = -1;
        if(StringUtil.isNotBlank(apiLog.getRequestContent())){
            uuidIndex = apiLog.getRequestContent().indexOf("intentionUuid");
        }
        if(uuidIndex > 0){
            String intentionUuid = apiLog.getRequestContent().substring(uuidIndex + 16, uuidIndex + 48);
            vo.setIntentionUuid(intentionUuid);
        }
        vo.setResponseContent(apiLog.getResponseContent());
        vo.setStatus("fail");
        if(StringUtils.isNotBlank(apiLog.getResponseContent())){
            if(apiLog.getResponseContent().indexOf("\"responseMessage\":\"success\"") > 0
            || apiLog.getResponseContent().indexOf("\"result\":\"1\"") > 0){
                vo.setStatus("success");
            }
        }
        vo.setOtherRelationId(apiLog.getOtherRelationId());
        vo.setBusinessType(apiLog.getBusinessType());
        vo.setRequestType(apiLog.getRequestType());
        vo.setCompanyId(apiLog.getCompanyId());
        vo.setOtherCompanyId(apiLog.getOtherCompanyId());
        vo.setPremisesId(apiLog.getPremisesId());
        vo.setPremisesName(apiLog.getPremisesName());
        vo.setPartnerId(apiLog.getPartnerId());
        vo.setPartnerName(apiLog.getPartnerName());
        vo.setBusinessTime(apiLog.getBusinessTime());
        vo.setAgentCompanyId(apiLog.getAgentCompanyId());
        vo.setRecordId(apiLog.getRecordId());
        vo.setRecordCount(apiLog.getRecordCount());
        vo.setRemark(apiLog.getRemark());
        return vo;
    }

    @Override
    public CommonResponse sendApiLogAgain (Long id) {
        CommonResponse response = new CommonResponse();
        ApiLog apiLog = apiLogRepository.findById(id).orElse(null);
        try {
            if (StringUtil.isNotBlank(apiLog.getUrl()) && StringUtil.isNotBlank(apiLog.getRequestContent())) {
                OtherCompany otherCompany = new OtherCompany();
                otherCompany.setCompanyUuid(apiLog.getOtherCompanyId());
                otherCompany.setIsDeleted(DelFlagEnum.UNDEL.getNo());
                List<OtherCompany> otherCompanyList = otherCompanyRepository.findAll(Example.of(otherCompany));
                if (otherCompanyList == null || otherCompanyList.size() == 0) {
                    response.setResponseMessage("公司相关信息为空,未发送请求");
                    return response;
                }
                String result = HttpUtil.doPostV10(apiLog.getUrl(), apiLog.getRequestContent(),
                        otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(),
                        otherCompanyList.get(0).getCompanyUuid());
                BaseResponseDto brDto = JSONObject.parseObject(result, BaseResponseDto.class);
                response.setResponseMessage(JSONObject.toJSONString(brDto));
            }
        } catch (Exception e) {
            response.setResponseMessage(JSONObject.toJSONString(e));
        } finally {
        }
        return response;
    }

}
